package com.sgu6.sgu6_machine.service;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

import androidx.annotation.Nullable;

import com.sgu6.netty.NettyClient;
import com.sgu6.redis.RedisClient;
import com.sgu6.redis.cache.MachineCache;
import com.sgu6.sgu6_machine.common.Constant;
import com.sgu6.sgu6_machine.config.MachineConfig;
import com.sgu6.sgu6_machine.container.MachineContainer;
import com.sgu6.sgu6_machine.event.DataloadEvent;
import com.sgu6.sgu6_machine.event.MachineReadyEvent;

import org.greenrobot.eventbus.EventBus;

/**
 * 机器网络初始化服务
 */
public class InitIntentS extends IntentService {

    public static final String TAG = InitIntentS.class.getCanonicalName();

    public InitIntentS(){
        super("name");
    }

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */

    public InitIntentS(String name) {
        super(name);

    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate: ===================");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.i(TAG, "onHandleIntent: ===================");
        RedisClient.init(MachineContainer.machineConfigDto.isBeta ? MachineContainer.machineConfigDto.redisUrl : Constant.REDIS_URI_DEV);
        MachineContainer.machineInfo = MachineCache.getMachineInfo(MachineContainer.machineConfigDto.isBeta ? MachineContainer.machineConfigDto.adminApiDomain : Constant.ADMIN_API_DOMAIN_DEV, MachineContainer.machineConfigDto.machineNo);
        if (MachineContainer.machineInfo != null && MachineContainer.machineInfo.getMerchantId() != null) {
            MachineContainer.machineConfigDto.merchantId = MachineContainer.machineInfo.getMerchantId();
            EventBus.getDefault().post(new MachineReadyEvent(true));
        } else {
            EventBus.getDefault().post(new MachineReadyEvent(false));

        }
        NettyClient.INSTANCE.connect(MachineContainer.machineConfigDto.machineNo, MachineContainer.machineConfigDto.appVersion, MachineContainer.machineConfigDto.isBeta ? MachineContainer.machineConfigDto.socketUrl : Constant.SOCKET_HOST_DEV, MachineContainer.machineConfigDto.isBeta ? Constant.SOCKET_PORT_BETA : Constant.SOCKET_PORT_DEV);
    }

}
